// 文件上传
const getBaseUrl = () => {
  const app = getApp();
  return app.globalData.baseUrl;
};

// 上传文件到服务器
const uploadFile = (filePath, url = '/api/user/uploadAvatar', name = 'file', formData = {}) => {
  return new Promise((resolve, reject) => {
    const app = getApp();
    wx.uploadFile({
      url: getBaseUrl() + url,
      filePath: filePath,
      name: name,
      header: {
        'Authorization': app.globalData.token || wx.getStorageSync('token') || ''
      },
      formData: formData,
      success: (res) => {
        console.log('上传结果:', res);
        if (res.statusCode === 200) {
          let data;
          try {
            data = JSON.parse(res.data);
            resolve(data);
          } catch (e) {
            console.error('解析上传结果失败:', e);
            reject(new Error('解析上传结果失败'));
          }
        } else {
          console.error('上传文件失败', res);
          reject(new Error('上传文件失败：' + res.errMsg));
        }
      },
      fail: (err) => {
        console.error('上传文件请求失败', err);
        reject(err);
      }
    });
  });
};

module.exports = {
  uploadFile,
  getBaseUrl
}; 